// 配置jwt组件
const jwt = require('jsonwebtoken')
// 导入全局的配置文件
const config = require('../../config')

// 导入bcryptjs密码加密模块
const bcrypt = require('bcryptjs')


// 配置数据库信息
const usersql = require('../../mysql.js')


// 生成随机id
const setId = require('../../assets/id.js')



// 提交账号密码登录
exports.login = (req, res) => {
    const user = req.body
    const sql = 'select * from users where studentid=?'
    usersql.query(sql, user.studentid, (err, results) => {
        if (err) return res.cc(err)
        // 对比提交的密码和数据库的密码，返回布尔值
        const compareResult = bcrypt.compareSync(user.password, results[0].password)
        if (compareResult) {
            // 登陆成功后配置JWT字符串
            console.log(results)
            const tokenStr = jwt.sign({ studentid: results[0].studentid }, config.secretKey, { expiresIn: config.expiresIn })
            res.send({ status: 200, message: '登录成功', data: tokenStr })
            console.log(tokenStr)
        } else {
            return res.cc('账号或密码错误')
        }
    })
}

// 注册新用户
exports.addUser = (req, res) => {
    // studentid studentname classname college password
    const newuser = req.body
    newuser.password = bcrypt.hashSync(newuser.password, 10)
    newuser.jointime = new Date ()
    const sql2 = 'insert into users set ?'
    const sql = 'insert into user_role(id,user_id,role_id) values ?'
    usersql.query(sql2, newuser, (err, results) => {
        if (err) return res.cc('用户已存在')
        if (results.affectedRows !== 0) {
            let itemid = setId(100000000,999999999)
            let item = [itemid,newuser.studentid,'5']
            let newroles = []
            newroles.push(item)
            usersql.query(sql, [newroles], (err, results) => {
                if (err) return res.cc(err)
                if (results.affectedRows === 0) {
                    res.cc('注册成功,添加用户角色失败')
                }
                res.send({ status: 200, message: '注册成功' })
            })
        } else {
            return res.cc('注册失败，请稍后再试')
        }
        
    })
}

// 根据姓名学号找回密码
exports.findUser = (req, res) => {
    const user = req.body
    const sql = 'select * from users where studentid=? and studentname=?'
    usersql.query(sql, [user.studentid,user.studentname], (err, results) => {
        if (err) return res.cc(err)
        if (results.length != 0) {
            res.send({ status: 200, message: '验证成功', data: results[0] })
        } else {
            return res.cc('验证失败，不存在该用户')
        }
    })
}
    